﻿using Restaurant.Model;
using System;
using System.Configuration;
using StackExchange.Redis;
using Newtonsoft.Json;
namespace Restaurant.Business
{
    public class RedisBusiness : IDisposable
    {
        public System.Collections.IDictionary RedisConfig = ConfigurationManager.GetSection("Redis") as System.Collections.IDictionary;
        public static ConnectionMultiplexer connectionMultiplexer = null;
        public static IDatabase _redisDB = null;
        public static ISubscriber subscriber = null;
        //默认缓存过期时间单位秒  
        public int secondsTimeOut = 1000 * 60;
        private int dbSize = 0;
        /// <summary>
        /// 初始化Redis连接
        /// </summary>
        ///dbSize 默认打开数据库：第一个库
        public RedisBusiness(int dbResultSize = 0)
        {
            if (connectionMultiplexer == null)
            {
                if (RedisConfig["Url"] != null && RedisConfig["Url"].ToString() != "")
                {
                    connectionMultiplexer = ConnectionMultiplexer.Connect(RedisConfig["Url"].ToString() + ",Password=n21ce");
                }
                if (connectionMultiplexer.IsConnected)
                {
                    if (_redisDB == null)
                    {
                        _redisDB = connectionMultiplexer.GetDatabase(dbResultSize);
                    }
                    subscriber = connectionMultiplexer.GetSubscriber();
                    this.dbSize = dbResultSize;
                }
            }
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="timeout">过期时间：默认不过期</param>
        /// <returns></returns>
        public virtual bool Set(string key, string value, int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                return _redisDB.StringSet(key, value, new TimeSpan(0, 0, secondsTimeOut));
            }
            return _redisDB.StringSet(key, value);
        }
        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual string Get(string key)
        {
            return _redisDB.StringGet(key);
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual bool Remove(string key)
        {
            return _redisDB.KeyDelete(key);
        }
        /// <summary>
        /// 检测Redis连接状态
        /// </summary>
        /// <returns></returns>
        public virtual bool IsRedisConnStatus()
        {
            if (connectionMultiplexer.IsConnected)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// Redis发布订阅  发布
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="channel"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public void RedisPub<T>(string channel, T msg)
        {
            if (subscriber != null)
            {
                long subCount = connectionMultiplexer.GetServer(RedisConfig["Url"].ToString()).SubscriptionSubscriberCount(channel);
                if (subCount > 0)
                {
                    subscriber.Publish(channel, JsonConvert.SerializeObject(msg));
                }
            }
        }

        /// <summary>
        /// Redis发布订阅  订阅
        /// </summary>
        /// <param name="subChannel"></param>
        public void RedisSub(string subChannel)
        {
            if (subscriber != null)
            {
                subscriber.Subscribe(subChannel, (channel, message) =>
                {
                    
                });
            }
        }
        /// <summary>
        /// Redis发布订阅  取消订阅
        /// </summary>
        /// <param name="channel"></param>
        public void Unsubscribe(string channel)
        {
            subscriber.Unsubscribe(channel);
        }
        /// <summary>
        /// Redis发布订阅  取消全部订阅
        /// </summary>
        public void UnsubscribeAll()
        {
            subscriber.UnsubscribeAll();
        }

        public void Dispose()
        {
            if (connectionMultiplexer != null)
            {
                connectionMultiplexer.Dispose();
            }
        }
    }
}
